package com.lxr5002.lxr5002production_test;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.factorytesttools.TestDataCallback;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AIDLTest extends Activity {


    TextView textView = null;


    private HandlerThread mWorkThread;
    private WorkHandler mWorkHandler;
    private Lock mLock = new ReentrantLock();
    StringBuilder buildervvvvvvv = new StringBuilder("");
    Context mContext;
    private com.android.factorytesttools.AuditRecord mAIDL_Service;
    private TestDataCallback mTestDataCallback = new TestDataCallback.Stub() {


        @Override
        public void onCallback(String filename, ParcelFileDescriptor pfd) throws RemoteException {
            Log.d("wst", "onCallback: pdf==" + pfd);
            Log.d("wst", "onCallback: filename==" + filename);
            Log.i("wst", "transactFileDescriptor: " + Thread.currentThread().getName());
            Log.i("wst", "transactFileDescriptor: calling pid:" + Binder.getCallingPid() + " calling uid:" + Binder.getCallingUid());

            StringBuilder builder = new StringBuilder("");
            try {
                ParcelFileDescriptor.AutoCloseInputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String line;

                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                    builder.append("\n");
                }
                Log.d("wst", "onCallback: builder==" + builder.toString());
                Log.d("wst", "onCallback: builder==" + builder.length());
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (builder.length() > 1000) {
                // SendMsg(filename + ":" + builder.length()+"个字符");
                buildervvvvvvv.append(filename + ":" + builder.length() + "个字符");
                buildervvvvvvv.append("\n");
            } else {
                buildervvvvvvv.append(filename + ":" + builder.toString());
                //builder.append("\n");

            }
            SendMsg(buildervvvvvvv.toString());

        }
    };
    //创建ServiceConnection的匿名类
    private ServiceConnection connection = new ServiceConnection() {

        //重写onServiceConnected()方法和onServiceDisconnected()方法
        //在Activity与Service建立关联和解除关联的时候调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (mAIDL_Service != null && mAIDL_Service.asBinder().isBinderAlive()) {
                try {
                    mAIDL_Service.unregisterListener(mTestDataCallback);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        //在Activity与Service建立关联时调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            android.util.Log.v("wst", " onServiceConnected ");
            //使用AIDLService1.Stub.asInterface()方法将传入的IBinder对象传换成了mAIDL_Service对象
            mAIDL_Service = com.android.factorytesttools.AuditRecord.Stub.asInterface(service);
            android.util.Log.v("wst", " mAIDL_Service== " + mAIDL_Service);
            android.util.Log.v("wst", " mTestDataCallback== " + mTestDataCallback);
            try {
                mAIDL_Service.registerListener(mTestDataCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_iccon);
        textView = (TextView) findViewById(R.id.textView);
        mWorkThread = new HandlerThread("ic_card_thread");
        mWorkThread.start();
        mWorkHandler = new WorkHandler(mWorkThread.getLooper());
        mContext = this;
        //Android5.0后无法只通过隐式Intent绑定远程Service
        Intent intent = new Intent("com.android.factorytesttools.action.AUDITRECORDSERVICE");
        //需要通过setPackage()方法指定包名
        intent.setPackage("com.android.factorytesttools");
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
        ((Button) findViewById(R.id.Button_space)).setText("获取使用空间百分比");
        ((Button) findViewById(R.id.Button_write)).setText("写审计记录");
        ((Button) findViewById(R.id.Button_getList)).setText("获取审计记录列表");
        ((Button) findViewById(R.id.button_getContent)).setText("读审计记录");
        ((Button) findViewById(R.id.Button_checkIcc)).setVisibility(View.GONE);
        ((Button) findViewById(R.id.button_checkPsam)).setVisibility(View.GONE);
        ((Button) findViewById(R.id.Button_RetsetIcc)).setVisibility(View.GONE);
        ((Button) findViewById(R.id.button_RetsetPsam)).setVisibility(View.GONE);
        ((Button) findViewById(R.id.Button_cmdIcc)).setVisibility(View.GONE);
        ((Button) findViewById(R.id.button_cmdPsam)).setVisibility(View.GONE);
        ((Button) findViewById(R.id.Button_version)).setVisibility(View.GONE);
        ((Button) findViewById(R.id.Button_update)).setVisibility(View.GONE);
        ((TextView) findViewById(R.id.textView)).setText("审计记录");
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        mWorkHandler.sendEmptyMessage(WorkHandler.POWER_OFF);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mAIDL_Service != null && mAIDL_Service.asBinder().isBinderAlive()) {
            try {
                mAIDL_Service.unregisterListener(mTestDataCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();

        mWorkHandler.removeCallbacksAndMessages(null);

        mWorkThread.quitSafely();

    }


    private class WorkHandler extends Handler {
        public static final int SELECT_ICC = 0;
        public static final int SELECT_PSAM = 1;
        public static final int CHECK_ICC = 2;
        public static final int CHECK_PSAM = 3;
        public static final int RETSET_ICC = 4;
        public static final int RETSET_PSAM = 5;
        public static final int CMD_ICC = 6;
        public static final int CMD_PSAM = 7;
        public static final int GET_VERSION = 8;
        public static final int MCU_UPDATE = 9;
        public static final int POWER_ON = 10;
        public static final int POWER_OFF = 11;
        public static final int WIFI_ON = 12;
        public static final int WIFI_OFF = 13;

        public static final int WIFI_ON1 = 14;
        public static final int WIFI_OFF1 = 15;

        public WorkHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            int ret = -1;
            switch (what) {
                case POWER_ON:

                    String mAuditRecordUsedpercent = null;
                    try {
                        mAuditRecordUsedpercent = mAIDL_Service.getAuditRecordUsedpercent();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    android.util.Log.v("wst", "getAuditRecordUsedpercent==" + mAuditRecordUsedpercent);
                    SendMsg("32G空间已使用" + mAuditRecordUsedpercent);
                    break;
                case POWER_OFF:
                    int writeAuditRecord = 0;
                    try {
                        //ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(new File(getCacheDir(), "file.iso"), ParcelFileDescriptor.MODE_READ_ONLY);
                        writeAuditRecord = mAIDL_Service.writeAuditRecord(" test ok ");
                        //writeAuditRecord = mAIDL_Service.transactFileDescriptor(fileDescriptor);//mAIDL_Service.writeAuditRecord(" test ok ");
                        //fileDescriptor.close();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    android.util.Log.v("wst", "writeAuditRecord==" + writeAuditRecord);
                    if (writeAuditRecord == 1) {
                        SendMsg("写审计记录 test ok 字符成功");
                    } else {

                        SendMsg("写审计记录失败");

                    }
                    break;
                case SELECT_ICC:

                    ArrayList<String> writeAuditRecord1 = null;
                    try {
                        writeAuditRecord1 = (ArrayList<String>) mAIDL_Service.getAuditRecordList();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }


                    StringBuffer sb = new StringBuffer();
                    sb.append("审计记录列表：\n");
                    for (int i = 0; i < writeAuditRecord1.size(); i++) {
                        android.util.Log.v("wst", "getAuditRecordList==" + writeAuditRecord1.get(i));
                        sb.append(writeAuditRecord1.get(i));
                        sb.append("\n");
                    }

                    SendMsg(sb.toString());

                    break;
                case SELECT_PSAM:
                    writeAuditRecord1 = null;
                    sb = new StringBuffer();
                    try {
                        writeAuditRecord1 = (ArrayList<String>) mAIDL_Service.getAuditRecordList();
                        sb.append("审计记录内容：\n");
                        buildervvvvvvv = new StringBuilder("");
                        buildervvvvvvv.append("审计记录内容：\n");
                        for (int i = 0; i < writeAuditRecord1.size(); i++) {
                            android.util.Log.v("wst", "getAuditRecordList==" + writeAuditRecord1.get(i));
                            mAIDL_Service.readAuditRecordCallback(writeAuditRecord1.get(i));
                          /*  android.util.Log.v("wst", "getAuditRecordList==" + writeAuditRecord1.get(i));
                            sb.append(writeAuditRecord1.get(i));
                            sb.append("\n");
                            String mreadAuditRecord = mAIDL_Service.readAuditRecord(writeAuditRecord1.get(i));
                            sb.append(mreadAuditRecord);
                            sb.append("\n");*/
                        }

                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    //SendMsg(sb.toString());
                    break;
                case CHECK_ICC:

                    break;
                case CHECK_PSAM:

                    break;
                case RETSET_ICC:


                    break;
                case RETSET_PSAM:

                    break;
                case CMD_ICC:

                    break;
                case CMD_PSAM:


                    break;

                case GET_VERSION:

                    break;

                case MCU_UPDATE:

                    break;

                case WIFI_ON:

                    try {
                        mAIDL_Service.setWiFiApEnable(true);
                        String setWiFiApSSidAndPasswd = mAIDL_Service.setWiFiApSSidAndPasswd("韦工你个老六", "00000000");
                        Log.e("setWiFiApSSidAndPasswd", setWiFiApSSidAndPasswd);
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                    break;

                case WIFI_OFF:
                    try {
                        mAIDL_Service.setWiFiApEnable(false);
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                    break;

                case WIFI_ON1:
                    try {
                        mAIDL_Service.kbsetWiFiEnable(true);
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case WIFI_OFF1:
                    try {
                        mAIDL_Service.kbsetWiFiEnable(false);
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                    break;

                default:
                    break;
            }
        }
    }

    private static final String HEX_STR = "0123456789ABCDEF";

    /**
     * 16进制字符串转字节数据
     *
     * @param hexStr 字符串
     * @return 字节数组
     */
    public static byte[] hexToByteArr(String hexStr) {
        char[] charArr = hexStr.toCharArray();
        byte[] btArr = new byte[charArr.length / 2];
        int index = 0;
        for (int i = 0; i < charArr.length; i++) {
            int highBit = HEX_STR.indexOf(charArr[i]);
            int lowBit = HEX_STR.indexOf(charArr[++i]);
            btArr[index] = (byte) (highBit << 4 | lowBit);
            index++;
        }
        return btArr;
    }


    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        for (int i = begin; i < begin + count; i++) {
            bs[i - begin] = src[i];
        }
        return bs;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length);
        byte[] var3 = bytes;
        int var4 = bytes.length;

        for (int var5 = 0; var5 < var4; ++var5) {
            byte aByte = var3[var5];
            String temp = Integer.toHexString(255 & aByte);
            if (temp.length() < 2) {
                sb.append(0);
            }

            sb.append(temp);
        }

        return sb.toString();
    }

    public void OnClickpoweron(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.POWER_ON);
    }

    public void OnClickpoweroff(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.POWER_OFF);
    }

    public void OnClickselectIcc(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.SELECT_ICC);

    }

    public void OnClickselectPsam(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.SELECT_PSAM);
    }

    public void OnClickcheckIcc(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.CHECK_ICC);
    }

    public void OnClickcheckPsam(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.CHECK_PSAM);

    }

    public void OnClickRetsetIcc(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.RETSET_ICC);

    }

    public void OnClickRetsetPsam(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.RETSET_PSAM);
    }

    public void OnClickcmdIcc(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.CMD_ICC);
    }

    public void OnClickcmdPsam(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.CMD_PSAM);
    }

    public void OnClickversion(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.GET_VERSION);
    }

    public void OnClickupdate(View view) {


        mWorkHandler.sendEmptyMessage(WorkHandler.MCU_UPDATE);
    }

    public void OnClickWifiOn(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.WIFI_ON);
    }

    public void OnClickWifiOff(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.WIFI_OFF);
    }

    public void OnClickWifiOn1(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.WIFI_ON1);
    }

    public void OnClickWifiOff1(View view) {
        mWorkHandler.sendEmptyMessage(WorkHandler.WIFI_OFF1);
    }


    private void SendMsg(String strInfo) {
        Message msg = new Message();
        msg.what = 1;
        Bundle b = new Bundle();
        b.putString("MSG", strInfo);
        msg.setData(b);
        handler.sendMessage(msg);
    }


    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle b = msg.getData();
                    String strInfo = b.getString("MSG");
                    textView.setText(strInfo);
                    Log.i("wei", strInfo);
                    break;
            }
        }
    };
}
